"""
产品序列化器 - 门户网站
"""

from rest_framework import serializers
from pecco_site.models import Product, ProductTranslation, ProductVariantImage


class ProductListSerializer(serializers.Serializer):
    """产品列表序列化器"""
    id = serializers.IntegerField()
    name = serializers.CharField()
    short_desc = serializers.CharField()
    cover = serializers.SerializerMethodField()
    hover = serializers.SerializerMethodField()
    tags = serializers.ListField(child=serializers.CharField())
    
    def get_cover(self, obj):
        """获取封面图"""
        if hasattr(obj, 'cover_image_url'):
            return obj.cover_image_url
        # 获取第一张图片作为封面
        first_image = obj.images.first()
        if first_image and first_image.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(first_image.image.url)
            return first_image.image.url
        return None
    
    def get_hover(self, obj):
        """获取悬停图"""
        if hasattr(obj, 'hover_image_url'):
            return obj.hover_image_url
        # 如果有 hover_image 字段
        if hasattr(obj, 'hover_image') and obj.hover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.hover_image.url)
            return obj.hover_image.url
        # 否则获取第二张图片
        images = obj.images.all()
        if len(images) > 1 and images[1].image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(images[1].image.url)
            return images[1].image.url
        return None


class ProductImageSerializer(serializers.Serializer):
    """产品图片序列化器"""
    id = serializers.IntegerField()
    url = serializers.CharField()
    alt_text = serializers.CharField(allow_blank=True)
    sort_order = serializers.IntegerField()


class ProductDetailSerializer(serializers.Serializer):
    """产品详情序列化器"""
    id = serializers.IntegerField()
    name = serializers.CharField()
    short_desc = serializers.CharField()
    description = serializers.CharField()
    usage = serializers.CharField()
    tags = serializers.ListField(child=serializers.CharField())
    images = ProductImageSerializer(many=True, read_only=True)
    specifications = serializers.JSONField()
    product_details = serializers.JSONField()
    
    # 变体相关字段可以后续添加
    # variants = ProductVariantSerializer(many=True, read_only=True)

